<?php
/**
 * 获取联动菜单接口
 */

header("Content-type:application/json;charset=utf-8");


defined('IN_PHPCMS') or exit('No permission resources.'); 
if(!$_GET['act']){
	echo '12';
	die;
}

// 安全验证机制
if($_GET['act'] != 'code2token')
	login_verify();

// 数字报栏目id
define('CAT_ID',7);

// userInfo
global $userInfo;

try{

	switch($_GET['act']) {
		case 'get_epaper':
			get_epaper();
		break;
		case 'get_date':
			get_date();
		break;
		case 'message_add':
			message_add();
		break;
		case 'code2token':
			code2token();
		break;
		case 'get_collect':
			get_collect();
		break;
		case 'collect':
			collect();
		break;
		case 'get_detail':
			get_detail();
		break;
		case 'get_userInfo':
			get_userInfo();
		break;
		case 'profile_photo_upload':
			profile_photo_upload();
		break;
		case 'set_name':
			set_name();
		break;
		case 'get_qrcode':
			get_qrcode();
		break;
		case 'test':
			test();
		break;
	}

}catch(Throwable $e){
	header("HTTP/1.1 501 failure");
	echo $e->getMessage();
	die;
}


/**
 * login 验证
 */
function login_verify(){

	$token = substr($_SERVER['HTTP_AUTHORIZATION'], 7);

	global $userInfo;

	$member_db = pc_base::load_model('weixin_member_model');

	$one = $member_db->get_one(['token'=>$token]);
	if(!$one){
		header("HTTP/1.1 401 auth fail");
		echo $token;
		die;
	}

	$userInfo = $one;
}
/**
 * 获取数字报数据
 */
function get_epaper() {

	$date = $_GET['date'];

	$db = pc_base::load_model('content_model');
	$db->set_catid(CAT_ID);

	// 获取某天的数字报
	if(!$date){
		$r = $db->get_one('', 'date', 'date desc');
		$date = $r['date'];
	}

	// 日期格式化
	$date = date('Y-m-d',strtotime($date));
	
 	$r = $db->select(['date'=>$date], 'page,page_name,page_image,date', '', 'page asc', 'page');
	if(!$r)
		die('[]');

	// 获取某天的热区数据
	$r2 = $db->select(['date'=>$date], 'page,points,title2,intro_title,thumb,author,id', '', '`listorder` desc,`id` asc');
	if(!$r2)
		die('[]');

	$ids = array_column($r2,'id');
	if(!$ids)
		die('[]');

	// 获取某天的热区数据 data 表格
	$db->table_name = $db->table_name.'_data';
	$r2d = $db->select('id in ('.implode(',',$ids).')', 'id');
	if(!$r2d)
		die('[]');

	// 版面信息拼接
	foreach($r as &$page){
		$page['article_list'] = [];
		foreach($r2 as $points){
			// 文章data 复制到文章
			// $points['image'] = '';
			// $points['content'] = '';
			// foreach($r2d as $content){
			// 	if($content['id'] == $points['id']){
			// 		$points['image'] = json_decode($content['image'],true);
			// 		$points['content'] = $content['content'];
			// 		continue;
			// 	}
			// }
			// 文章数据追加到版面
			if($points['page'] == $page['page']){
				$page['article_list'][] = $points;
			}
		}
	}

	echo json_encode($r ,JSON_UNESCAPED_UNICODE);
}

/**
 * 获取本月有数据的日期
 */
function get_date(){
	// 获取某天的数字报
	$db = pc_base::load_model('content_model');
	$db->set_catid(CAT_ID);

	$sql = '';

	// 查询开始时间
	$start_date = $_GET['start_date'];
	if($start_date){
		$start_date = date("Y-m-d", strtotime($start_date));
		if($sql)
			$sql .= ' and ';
		$sql .= "date>='".$start_date."'";
	}
	
	// 查询结束时间
	$end_date = $_GET['end_date'];
	if($end_date){
		$end_date = date("Y-m-d", strtotime($end_date));
		if($sql)
			$sql .= ' and ';
		$sql .= "date<='".$end_date."'";
	}
	
	$r = $db->select($sql, "`date`",'','date desc','date');
	if(!$r)
		die('[]');

	$dates = array_column($r,'date');
	echo json_encode($dates, JSON_UNESCAPED_UNICODE);
}

/**
 * 添加留言
 */
function message_add(){
	global $userInfo;
	
	$messageDb = pc_base::load_model('epaper_message_model');
	//
	$input = file_get_contents("php://input");
	$json = json_decode($input, true);

	$content = safe_replace($json['content']);
	$ins = [
		'user_name'=>$userInfo['name'],
		'content'=>$content,
	];

	$messageDb->insert($ins,true);
	echo json_encode([]);
}


/**
 * code 换取 token
 */
function code2token(){
	$db = pc_base::load_model('access_token_model');
	$one = $db->get_one(1);

	$APPID = $one['appid'];
	$SECRET = $one['secret'];
	$JSCODE = $_GET['code'];

	$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$APPID&secret=$SECRET&js_code=$JSCODE&grant_type=authorization_code";
	$content = file_get_contents($url);
	$array = json_decode($content, true);

	$openid = $array['openid'];
	$session_key = $array['session_key'];
	$unionid = $array['unionid'];
	$errcode = $array['errcode'];
	$errmsg = $array['errmsg'];

	// 检查错误
	if($errcode != 0){
		header("HTTP/1.1 401 weixin error");
		die($errmsg);
	}


	$member_db = pc_base::load_model('weixin_member_model');
	$two = $member_db->get_one(['openid'=>$openid]);
	if(!$two){
		// 若不存在用户则新增一个
		$ins = [
			'unionid'=>$unionid,
			'openid'=>$openid,
			'session_key'=>$session_key,
		];

		$member_db->insert($ins);
		// 再次获取member
		$two = $member_db->get_one(['openid'=>$openid]);
	}

	$token = md5($openid . time());
	// 重设token
	$member_db->update(['token'=>$token, 'last_ip'=>ip(), 'last_login_time'=>date('Y-m-d H:i:s'), ], ['openid'=>$openid]);

	$rtn = [
		'token'=>$token,
	];

	echo json_encode($rtn ,JSON_UNESCAPED_UNICODE);
}

/**
 * 获取收藏
 */
function get_collect(){

	$page = $_GET['page'];
	$limit = $_GET['limit'];
	if(!$page)
		throw new Exception('page不能为空');
	if(!$limit)
		throw new Exception('page不能为空');

	$offset = ($page - 1) * $limit;

	$model = pc_base::load_model('weixin_member_collect_model');
	global $userInfo;

	$openid = $userInfo['openid'];

	/**
	 * sql 安全处理
	 */
	$offset = safe_replace($offset);
	$limit = safe_replace($limit);
	$openid = safe_replace($openid);

	$sql = <<<EOF
	SELECT
		weixin_member_collect.id,
		weixin_member_collect.epaper_id,
		title2,
		author,
		date,
		thumb,
		image,
		true as is_collected
	FROM
		weixin_member_collect
		INNER JOIN epaper ON epaper.id = weixin_member_collect.epaper_id 
		INNER JOIN epaper_data on epaper_data.id = weixin_member_collect.epaper_id
	WHERE
		weixin_member_collect.openid = '$openid'
	GROUP BY
		weixin_member_collect.epaper_id
	ORDER BY
		id DESC
	limit $offset,$limit
EOF;

	$model->query($sql);
	$arr = $model->fetch_array();
	echo json_encode($arr, JSON_UNESCAPED_UNICODE);
}
/**
 * 收藏接口
 */
function collect(){

	$input = file_get_contents("php://input");
	$array = json_decode($input, true);

	$type = $array['type']??$_GET['type'];
	
	switch($type){
		case 'add':
			add_collect();
		break;
		case 'delete':
			delete_collect();
		break;
		default:
			throw new Exception('发生错误type');
	}
}

/**
 * 设置收藏
 */
function add_collect(){
	global $userInfo;
	$openid = $userInfo['openid'];

	$input = file_get_contents("php://input");
	$array = json_decode($input, true);

	$epaper_id = $array['epaper_id'];

	$epaper_id = safe_replace($epaper_id);
	$openid = safe_replace($openid);


	$model = pc_base::load_model('weixin_member_collect_model');

	$ins = [
		'epaper_id'=>$epaper_id,
		'openid'=>$openid,
	];

	$one = $model->get_one($ins);
	if(!$one)
		$model->insert($ins);

	echo json_encode([]);
}

/**
 * 删除收藏
 */
function delete_collect(){

	$input = file_get_contents("php://input");
	$array = json_decode($input, true);

	global $userInfo;
	$openid = $userInfo['openid'];

	$epaper_id = $array['epaper_id'];

	$epaper_id = safe_replace($epaper_id);
	$openid = safe_replace($openid);


	$model = pc_base::load_model('weixin_member_collect_model');

	$re = $model->delete(['epaper_id'=>$epaper_id, 'openid'=> $openid]);

	echo json_encode([]);
}

/**
 * 内容
 */
function get_detail(){
	global $userInfo;
	$openid = $userInfo['openid'];

	$epaper_id = $_GET['epaper_id'];

	$epaper_id = safe_replace($epaper_id);
	$openid = safe_replace($openid);

	$db = pc_base::load_model('content_model');
	$db->set_catid(CAT_ID);

	$r = $db->get_one(['id'=>$epaper_id], 'id,title,title2,description,thumb,intro_title,sub_title,author,page,page_name,date');
	if(!$r)
		die('[]');

	// 获取某天的热区数据 data 表格
	$table_name = $db->table_name;
	$db->table_name = $db->table_name.'_data';
	$rd = $db->get_one(['id'=>$epaper_id], 'id,image,content,relation,audio');

	// 连接转为全连接
	$rd['content'] = str_replace('src="uploadfile','src="https://lab.chinaluan.com/uploadfile',$rd['content']);
 
	$rt = array_merge($r,$rd);
	// 推荐新闻
	$relation_arr = [];
	$relation_ids = array_filter(explode("|", $rt['relation']));
	if($relation_ids){
		$db->table_name = $table_name;
		$relation_arr = $db->select('id in ('.implode(',',$relation_ids).')', "id,title2,intro_title,sub_title,thumb,author,page,page_name,date");
	}

	$rt['relation'] = $relation_arr;
	
	// 查询是否收藏了
	$model = pc_base::load_model('weixin_member_collect_model');
	$two = $model->get_one(['epaper_id'=>$epaper_id,'openid'=>$openid]);


	$rt['is_collected'] = false;
	if($two)
		$rt['is_collected'] = true;

	// 加入统计数据 detail_log
	$detail_log_db = pc_base::load_model('epaper_detail_log_model');

	$ins = [
		'epaper_id'=>$epaper_id,
		'epaper_title'=>$rt['title'],
		'epaper_date'=>$rt['date'],
		'weixin_member_id'=>$userInfo['id'],
		'weixin_member_name'=>$userInfo['name'],
		'weixin_member_openid'=>$userInfo['openid'],
	];

	$detail_log_db->insert($ins);

	echo json_encode($rt, JSON_UNESCAPED_UNICODE);
}
/**
 * 获取用户头像，昵称
 */
function get_userInfo(){
	global $userInfo;
	
	$name = $userInfo['name'];
	$profile_photo = $userInfo['profile_photo'];
	$is_admin = $userInfo['is_admin'];

	$rt = [
		'name'=>$name,
		'profile_photo'=>$profile_photo,
		'is_admin'=>$is_admin,
	];

	echo json_encode($rt, JSON_UNESCAPED_UNICODE);
}

/**
 * profile_photo upload
 * 用户头像上传
 */
function profile_photo_upload(){

	global $userInfo;

	// 判断文件夹是否存在
	$upload_base = 'uploadfile/profile_photo/'.date('Y').'/'.date('md').'/';
	if(!is_dir($upload_base)){
		$r = mkdir($upload_base,0777,true);
		if(!$r)
			throw new Exception('创建文件夹失败');
	}

	if(!isset($_FILES['file']))
		throw new Exception('未上传文件');

	$file = $_FILES['file'];
	$ext = end(explode('.',$file['name']));

	// allow ext
	$allow_ext = [
		'jpg','jpeg','png'
	];

	if(!in_array($ext, $allow_ext))
		throw new Exception("非法文件类型：$ext");

	$tmp_name = $file['tmp_name'];

	if(!is_uploaded_file($tmp_name))
		throw new Exception("非法操作");

	$new_name = $upload_base.uniqid().'.'.$ext;

	if(!move_uploaded_file($tmp_name, $new_name))
		throw new Exception("头像上传失败");

	// 保存头像信息到用户
	$model = pc_base::load_model('weixin_member_model');
	$one = $model->get_one(['openid'=>$userInfo['openid']]);
	if(!$one)
		throw new Exception("头像上传失败2");
	
	$r = $model->update(['profile_photo'=> $new_name], ['openid'=> $userInfo['openid']]);
	if(!$r)
		throw new Exception("头像设置失败3");

	$rt = [
		'url'=>$new_name
	];
	
	echo json_encode($rt, JSON_UNESCAPED_UNICODE);
}

/**
 * set_name
 */
function set_name(){

	global $userInfo;

	$input = file_get_contents("php://input");
	$array = json_decode($input, true);


	$name = $array['name']??'';
	$name = safe_replace($name);

	$model = pc_base::load_model('weixin_member_model');

	$r = $model->update(['name'=> $name], ['openid'=> $userInfo['openid']]);
	if(!$r)
		throw new Exception('设置用户名失败');
	
	echo '[]';
}

function get_qrcode(){
	$env_version = $_GET['env_version']?:'trial';
	$id = $_GET['id']?:'0';
	
	$db = pc_base::load_model('access_token_model');
	$rtn = $db->get_qrcode($id, 'pages/contentInfo/contentInfo',$env_version);
	header("Content-type: image/png");	
	echo $rtn;
}

/**
 * test
 */
function test(){
	// get_collect();
	global $userInfo;
	var_dump($userInfo);
}
